<?php
namespace app\admin\business;

use app\admin\validate\AdminUserValidate;
use app\common\model\AdminUser as AdminModel;

class AdminUser
{
    protected $adminUserModel = null;

    public function __construct()
    {
        $this->adminUserModel = new AdminModel();
    }
    
    public function getAdminUserByUserInfo(array $userInfo)
    {
        // 登录验证
        $validate = new AdminUserValidate();
        if (!$validate->scene('adminuser')->check($userInfo)) {
            throw new \think\Exception($validate->getError());
        }

        $adminUser = $this->getAdminUserByUserName($userInfo['username']);

        // 验证码密码是否正确
        if ($adminUser->password != md5($userInfo['password'] . '_214')) {
            throw new \think\Exception('密码错误!');
        }

        // 需要更新的字段
        $updata = [
            'update_time' => time(),
            'last_login_time' => time(),
            'last_login_ip' => request()->ip()
        ];
        $result = $this->adminUserModel->UpdateAdminUserById($adminUser->id, $updata);
        if (empty($result)) {
            throw new \think\Exception('更新数据失败!');
        }

        // 将数据传入session
        session('admin_user', $adminUser);
        
        return true;
    }

    // 获取用户信息
    public function getAdminUserByUserName($username)
    {
        $adminUser = $this->adminUserModel->getUserInfoByUserName($username);

        // 判断该用户是否存在
        if (empty($adminUser) || $adminUser->status != 1) {
            return [];
        }
        return $adminUser;
    }
}
